import Vue from 'vue'
import DictData from './DictData'
import { getDictsBatch as getDictsBatch } from '@/api/system/dict/data'
import {Message} from "element-ui";


const DEFAULT_DICT_OPTIONS = {
  types: [],
}

/**
 * @classdesc 字典
 * @property {Object} label 标签对象，内部属性名为字典类型名称
 * @property {Object} dict 字段数组，内部属性名为字典类型名称
 * @property {Array.<DictMeta>} _dictMetas 字典元数据数组
 */
export default class Dict {
  constructor() {
    this.owner = null
    this.label = {}
    this.type = {}
  }

  init(options) {

    if (options === undefined) {
      throw new Error('need dict types')
    }

    let dicts = options
    if (dicts instanceof Array) {
      dicts.forEach(item => {
        Vue.set(this.label, item, {})
        Vue.set(this.type, item, [])
      })
      dicts = dicts.join(",")
    }else{
      Vue.set(this.label, dicts, {})
      Vue.set(this.type, dicts, [])
    }

    const ps = []
    getDictsBatch(dicts).then(res => {
      res.data.forEach(d => {
        const data = new DictData(d["dictLabel"], d["dictValue"], d);
        this.type[d.dictType][this.type[d.dictType].length] = data;
        Vue.set(this.label[d.dictType], data.value, data.label)
        ps.push(data)
      })
    }).catch(r => {
      console.error(r)
      Message.error('批量查询字典数据错误！')
    })
    return Promise.all(ps)
  }
}
